package com.thinkverse.user.controller;

import com.thinkverse.user.dto.*;
import com.thinkverse.user.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 认证相关接口
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "认证模块")
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final AuthService authService;

    @PostMapping("/register/code")
    @Operation(summary = "发送注册验证码")
    public ApiResponse<String> sendRegisterCode(@Valid @RequestBody VerifyCodeRequestDTO request) {
        log.info("发送注册验证码 {}", request);
        authService.sendRegisterCode(request);
        return ApiResponse.success("验证码已发送至邮箱，15分钟内有效");
    }

    @PostMapping("/register")
    @Operation(summary = "注册账户")
    public ApiResponse<Object> register(@Valid @RequestBody RegisterRequestDTO request) {
        Long userId = authService.register(request);
        return ApiResponse.success(Map.of(
                "userId", userId,
                "username", request.getUsername(),
                "email", request.getEmail()
        ));
    }

    @PostMapping("/login")
    @Operation(summary = "登录")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequestDTO request) {
        LoginResponse resp = authService.login(request);
        return ApiResponse.success(resp);
    }

    @PostMapping("/logout")
    @Operation(summary = "退出登录")
    public ApiResponse<String> logout(HttpServletRequest req) {
        String authHeader = req.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            authService.logout(authHeader.substring(7));
        }
        return ApiResponse.success("退出成功");
    }
}
